package net.sh.dpinfrastructure.sql;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.sql.DataSource;

import net.sh.dpinfrastructure.exception.DPException;
import net.sh.dpinfrastructure.exception.DPException.Level;
import net.sh.dpinfrastructure.exception.DPException.Modal;
import net.sh.dpinfrastructure.exception.DPException.Type;
import net.sh.dpinfrastructure.log.DPLogger;


/**
 * 
 * jdbc 操作类
 * @author Lancer
 * @date 2015年8月2日下午8:33:36 sql（mysql）操作类
 *
 */
public class DPSql {

    private static final DPLogger LOGGER = new DPLogger(DPSql.class);
    
    private DataSource dataSource;
    
    public DPSql(DataSource dataSource) {
        this.dataSource = dataSource;
    }
    
    public Connection getConnection() {
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            LOGGER.fatal("获取数据库连接失败", e);
            throw new DPException(DPException.Level.ERROR, DPException.Modal.DATAPLATFORM, DPException.Type.DB_CONNECTION, "获取数据库连接失败");
        }
    }
    
    public void closeConnection(Connection connection) {
        try {
            if (connection != null && !connection.isClosed()) {
                connection.close();
            }
        } catch (SQLException e) {
            throw new DPException(Level.ERROR, Modal.DATAPLATFORM, Type.DB_CONNECTION, "数据库连接异常");
        }
    }
    
    public void closeStatement(Statement statement) {
        try {
            if (statement != null && !statement.isClosed()) {
                statement.close();
            }
        } catch (SQLException e) {
            throw new DPException(Level.ERROR, Modal.DATAPLATFORM, Type.DB_CONNECTION, "数据库连接异常");
        }
    }

    public void closeResultSet(ResultSet rs) {
        try {
            if (rs != null && !rs.isClosed()) {
                rs.close();
            }
        } catch (SQLException e) {
            throw new DPException(Level.ERROR, Modal.DATAPLATFORM, Type.DB_CONNECTION, "数据库连接异常");
        }
    }
    
    public void closeDBResource(ResultSet rs, Statement statement, Connection connection) {
        closeResultSet(rs);
        closeStatement(statement);
        closeConnection(connection);
    }

}
